// pages/tabbar/growup/growup.js
import { bindUser } from "../../../utils/bindUser.js";
import { CommonModel } from "../../../api/api-common/commonModel.js";
import { GrowupModel } from "../../../api/api-growup/growupModel.js";
import { getFileType } from "../../../utils/index.js"
const growupModel = new GrowupModel()
const commonModel = new CommonModel()
const App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLogin: 0, // 0: 加载中， 1：已登录， 2：未登录
    showOptions: false,
    studentOptions: [],
    studentName: "全部学员",
    studentId: 0, // 选中的学员id
    pageNum: 1,
    total: 0,
    triggered: false,
    tempDatas: [], // 临时存储
    objTableData: {}, // 数据对象
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    console.log("我是成长")
    this.key = wx.eventBus.newKey()
    wx.eventBus.on({
      key: this.key,
      event: 'change',
      listener: (params) => {
        this.setData({
          isLogin: params.isLogin
        })
        wx.nextTick(() => {
          this.setData({
            isLogin: params.isLogin
          })
        })
        if (this.data.isLogin == 1) {
          this.setData({
            triggered: false,
            pageNum: 1,
            tempDatas: []
          })
          this.getStudentInfos();
          // 获取成长列表
          this.getGrowthList()
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      isLogin: App.globalData.isLogin
    })
    console.log("成长：", this.data.isLogin)
    if (this.data.isLogin == 1) {
      this.setData({
        triggered: false,
        pageNum: 1,
        tempDatas: []
      })
      this.getStudentInfos();
      // 获取成长列表
      this.getGrowthList()
    }

  },

  // 获取学员信息
  getStudentInfos() {
    commonModel.getStudentInfosApi().then(res => {
      this.setData({
        studentOptions: res,
      })
    })
  },

  // 获取成长列表
  getGrowthList() {
    growupModel.getGrowthListtApi({ studentId: this.data.studentId, pageNum: this.data.pageNum, pageSize: 10 }).then(res => {
      if (res.rows && res.rows.length > 0) {
        res.rows.forEach(item => {
          item["linkData"] = item.link == null ? [] : item.link.split(",")
        })
        res.rows.forEach(item => {
          let mp3Datas = [];
          let otherDatas = [];

          item.linkData.forEach(k => {
            if ('radio' == getFileType(k)) {
              // 音频
              mp3Datas.push(k)
            }
            else if ('video' == getFileType(k)) {
              otherDatas.push({
                type: "video",
                url: k
              })
            }
            else if ("image" == getFileType(k)) {
              otherDatas.push({
                type: "image",
                url: k
              })
            }
            item['mp3Datas'] = mp3Datas;
            item['otherDatas'] = otherDatas;
          })
        })
      }

      let rows = this.data.tempDatas;
      rows.push(...res.rows);
      this.setData({
        tempDatas: rows,
        total: res.total,
      })
      // 数据格式整合
      let obj = {}
      this.data.tempDatas.forEach(item => {
        if (obj.hasOwnProperty(item.createDateShow)) {
          obj[item.createDateShow].push(item)
        }
        else {
          obj[item.createDateShow] = [item]
        }
      })
      this.setData({
        objTableData: obj
      })
    })
  },
  // 上拉加载
  getMoreData() {
    if (this.data.total > this.data.tempDatas.length) {
      this.setData({
        pageNum: this.data.pageNum + 1
      })
      this.getGrowthList()
    }
  },
  // 下拉刷新
  refreshData() {
    this.setData({
      triggered: false,
      pageNum: 1,
      tempDatas: []
    })
    this.getGrowthList()
  },
  lookBigImage(e) {
    wx.previewImage({
      urls: [e.currentTarget.dataset.query],
    })
  },
  // 选择学员
  selectStudent() {
    this.setData({
      showOptions: true
    })
  },
  onConfirmPicker(e) {
    const { value } = e.detail;
    this.setData({
      studentId: value.studentId,
      studentName: value.studentName,
      showOptions: false,
      triggered: false,
      pageNum: 1,
      tempDatas: []
    })
    this.getGrowthList()
  },
  onCancelPicker() {
    this.setData({
      showOptions: false
    })
  },

  // 去评价学员详情
  navigateToStudentDetail(e) {
    const param = JSON.stringify(e.currentTarget.dataset.query);
    wx.navigateTo({
      url: `/pages/evaluateStudentDetail/evaluateStudentDetail?param=${param}`,
    })
  },

  // 第一步：授权获取手机号
  async getPhoneNumber(e) {
    const { bind_code } = await bindUser(e);
    if (bind_code == 200) {
      // 授权绑定成功, 获取用户信息
      commonModel.getInfosApi().then(result => {
        // 绑定了用户名
        App.globalData.username = result.name == null || result.name == "" ? "微信授权用户" : result.name;
        App.globalData.openid = result.openid;
        App.globalData.mpid = result.mpid;
        App.globalData.isLogin = 1;
        // this.setData({
        //   isLogin: 1
        // })
        wx.eventBus.post({
          params: {
            isLogin: 1
          },
          event: 'change'
        })
        wx.switchTab({
          url: '/pages/tabbar/growup/growup'
        })
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})